<template>
  <el-container>
    <!-- <RegionTree style="margin-top: 16px" @on-choose-region="filetrRegion" /> -->
    <el-main>
      <div class="default-main ba-table-box">
        <TableHeader
          :buttons="['refresh', 'comSearch']"
          :quick-search-placeholder="placeholder"
          @action="baTable.onTableHeaderAction"
        />
        <!-- 表格 -->
        <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
        <Table ref="tableRef" @action="baTable.onTableAction" />
      </div>
    </el-main>
  </el-container>
</template>
<script setup lang="ts">
import {
  ref,
  provide,
  onMounted,
  markRaw,
  onBeforeUnmount,
  reactive,
  inject,
} from "vue";
import baTableClass from "@/utils/baTable";
import { baTableApi, operatorShowOff } from "@/utils/common"; // 导入表格api方法生成器
import { DeviceMAccess } from "@/api/backend/index";
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import type { TableRow } from "@/utils/baTable"; //表格列行类型
import { useAccess } from "@/store/backend/DeviceM/access";
import { useBusiness } from "@/store/backend/BusinessM/info";
import { useRouter, useRoute, onBeforeRouteUpdate } from "vue-router";
import { useRegion } from "@/store/backend/SysM/region";
import _ from "lodash";
import { useDictionary } from "@/store/backend/tool/dictionary";
import { getDictData } from "@/utils/common";
import { useCarbon } from "@/store/backend/EquipM/activeCarbon";
import Standard from "./standard.vue";

var timer: NodeJS.Timer;

const placeholder = ref<string>("模糊搜索");
const tableRef = ref();
const access = useAccess();
const carbon = useCarbon();
const region = useRegion();
const router = useRouter();
const route = useRoute();
const dictionary = useDictionary();
const standard = inject("standard") as any;
const navTabs = inject("navTabs") as any;

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + DeviceMAccess)
      ? (navTabs as any).pageSizeMap.get(route.path + DeviceMAccess)
      : 10;
  }
  return 10;
};

const formRef = ref();
//全局事件总线
const { proxy } = useCurrentInstance();
const baTable = new baTableClass(
  new baTableApi(DeviceMAccess), //this.api = api菜单管理相关
  {
    pk: "id", //设备id
    column: [
      // { type: "selection", width: "100", align: "center", operator: false },
      {
        show: filedShowOff("code"),
        label: "设备编号",
        prop: "code",
        align: "center",
        operatorPlaceholder: "精确搜索",
      },
      {
        show: filedShowOff("cname"),
        label: "企业名称",
        prop: "cname",
        align: "center",
        operatorPlaceholder: "模糊搜索",
      },
      {
        label: "巡检标准",
        prop: "",
        align: "center",
        render: "customRender",
        customRender: markRaw(Standard),
        operator: false,
      },
    ],
    filter: {
      regions: [region.regionIds] + "",
      institution: access.companyid ? access.companyid : "" + "",
      cname: route.query.cname,
      estate: route.query.estate,
      state: route.query.state,
      openState: route.query.openState,
      pageSize: pageSizeKeep(),
    },
    acceptQuery: false,
  },
  {},
  // 操作前置方法列表，返回false则取消原操作
  {
    // getList: () => {
    //   /**
    //    * 查询设备接入数据前将企业列表数据转为map格式
    //    * 1  判断所属企业列表数据是否为空
    //    */
    //   const business = useBusiness();
    //   const { companyList, companiesMap } = business;
    //   if (companyList.length === 0) {
    //     //为空就重新获取企业列表数据
    //     business.getCompanyList().then((res) => {
    //       timer = setTimeout(() => {
    //         List();
    //       }, 300);
    //     });
    //   }
    //   business.getCompanyList(); //翻页需要不触发List方法
    // },
  },
  // 操作后置方法列表，先执行表格本身的查看、删除、编辑、双击、等，再执行本处添加的后置操作
  {}
);
const List = () => {
  /**
   * 如果所属企业列表数据为空 不使用tabel类默认getList方法来获取数据
   *  使用List()方法保证在处理完企业列表之后或者所属企业列表数据为空的情况下获取数据
   */
  access
    .getAccessList({
      pageNum: 1,
      pageSize: 10,
      regions: region.regionIds + "",
      institution: access.companyid ? access.companyid : "" + "",
    })
    .then((res: any) => {
      baTable.table.data = res.rows;
      baTable.table.total = res.total;
      baTable.table.loading = false;
    });
};
//打开初始化表单
// const originButtonClick = (name: string, row: anyObj) => {
//   //打开初始化表单
//   baTable.form.operate = name;
//   let temp = { ecode: row.code, eid: row.id };
//   access.item = row;
//   let obj = _.cloneDeep(row);
//   obj.state = 1; //改为离线数据
//   access.item = obj;
//   console.log("access.item", access.item);
//   baTable.form.items = Object.assign(baTable.form.items, temp);
// };
//跳转详情页
const infoButtonClick = (id: number, row: any) => {
  console.log("id", id, "row", row);
  getCarbonDetail(id);
  access.$patch((state) => {
    state.single = row;
  });
  router.push({ path: "/admin/DeviceM/accessDetail", query: { eid: row.id } });
};
const getCarbonDetail = (id: any) => {
  carbon.getCarbonInfo({ eid: id }).then((res: any) => {
    console.log("跳转详情页", res);
  });
};
// interface Region {
//   address: string | null;
//   addressDetail: string | null;
//   areaFlag: string | null;
//   areaId: number;
//   areaName: string | null;
//   areaNo: string | null;
//   children: Region[];
//   createBy: string | null;
//   createTime: string | null;
//   endTime: string | null;
//   params: any;
//   parentId: number;
//   searchValue: string | null;
//   startTime: string | null;
//   updateBy: string | null;
//   updateTime: string | null;
// }
//接收区域树传递过来的数据
// const filetrRegion = (row: Region, node: any) => {
//   if (node.checkedKeys.length == 0) {
//     //表示取消选择直接调用刷新表单方法
//     baTable.comSearch.form = Object.assign(baTable.comSearch.form, {
//       regions: region.regionIds + "",
//     });
//     baTable.onTableHeaderAction("refresh", {});
//   } else {
//     baTable.comSearch.form.regions = node.checkedKeys + "";
//     baTable.getList(DeviceMAccess);
//   }
// };
onBeforeRouteUpdate((to, form, next) => {
  console.log("当前路由啊,", route);
  next(false);
});

//获取菜单状态的字典
const getMenuStatus = () => {
  dictionary.getDictInfo("device_online_status").then((res: any) => {
    // state.statusDict = getDictData(res);
    dictionary.tag = getDictData(res);
    console.log("获取菜单状态的字典", dictionary.tag);
  });
};
getMenuStatus();

onMounted(() => {
  console.log("access.switch!!!!", access.switch);

  // proxy.eventBus.emit("pointer"); //el-table显示双击小手套
  //将table的ref给到table类
  baTable.table.ref = tableRef.value;
  baTable.mount();
  //延后查询 等待查询的前置操作
  baTable.getList(DeviceMAccess);
  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow }) => {
      if (!baTable.activate) return;
      //用户点击初始化给活性炭监控
      if (data.name == "origin") {
        // console.log("初始化", data.row);
        // //在初始化之前判断是否含有数据，有数据就提示无法多次初始化 数据为空打开表单
        // access
        //   .getDetail(data.row.id)
        //   .then((res: any) => {
        //     console.log("获取的数据", res);
        //     if (res.rows.length !== 0) {
        //       ElMessageBox.confirm("设备已初始化完成,无法再次初始化", "提示", {
        //         confirmButtonText: "确认",
        //         cancelButtonText: "取消",
        //         type: "warning",
        //       });
        //     } else {
        //       // originButtonClick(data.name, data.row);
        //     }
        //   })
        //   .catch((err) => {});
      } else if (data.name == "accessInfo") {
        //详情页面
        infoButtonClick(
          (data.row as TableRow)[baTable.table.pk!],
          data.row as any
        );
      }
    }
  );
  proxy.eventBus.emit("clear");
});
onBeforeUnmount(() => {
  console.log("触发onBeforeUnmount");
  clearTimeout(timer);
  proxy.eventBus.emit("clear");
  proxy.eventBus.off("toMonitor");
});
// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
provide("dictionary", dictionary);
</script>
<style lang="scss" scoped>
.el-main {
  padding: 0;
}
.default-main {
  margin: var(--ba-main-space) var(--ba-main-space) 60px var(--ba-main-space);
}
</style>
